package com.hrm.controller;

import com.hrm.entity.Employee;
import com.hrm.entity.User;
import com.hrm.module.Dto;
import com.hrm.service.lxy.EmpService;
import com.hrm.service.xfl.EmployeeService;
import com.hrm.service.xfl.UserService;
import com.hrm.utils.BaseCryptographyUtils;
import com.hrm.utils.Constants;
import com.hrm.utils.DtoUtil;
import com.hrm.utils.core.FaceClient;
import org.apache.log4j.Logger;
import org.apache.poi.ss.formula.functions.T;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;

/**
 * 公共页面，登录，退出等
 *
 * @author 李雪阳
 * @version 1.0
 * @date 2020/8/1 17:02
 */
@Controller
public class CommonController {
    public static final String APP_ID = "21761688";
    public static final String API_KEY = "vvdrmleFZDsBavs6WESGcLsa";
    public static final String SECRET_KEY = "fsqddwb2A5G6aZmBhoMIB6mGhff7RxWT";
    private static String BASE64 = "BASE64";
    private Logger logger = Logger.getLogger(CommonController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmpService empService;
    //从类路径中加载文件
    private static Properties properties = null;
    private static String aesKey = "chongcibchongcibchongcibchongcib";
    private static String desKey = "chongcibchongcibchongcibchongcibchongcibchongcibchongcibchongcib";

    static {
        try {
            properties = PropertiesLoaderUtils.loadAllProperties("key.properties");
            aesKey = properties.getProperty("aeskey");
            desKey = properties.getProperty("deskey");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 登录页
     *
     * @return
     */
    @GetMapping({"/", "login", "loginForm"})
    public String loginForm() {
        return "loginForm";
    }

    /**
     * 管理员欢迎界面
     *
     * @return
     */
    @RequestMapping("/welcome")
    public String welcome() {
        return "welcome";
    }

    /**
     * 员工欢迎页面
     *
     * @return
     */
    @RequestMapping("/welcomeEmployee")
    public String welcomeI() {
        return "welcomeEmployee";
    }

    /**
     * 登录user/employee
     *
     * @param loginname
     * @param password
     * @param tip
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public String doLogin(@RequestParam("loginname") String loginname, @RequestParam("password") String password, @RequestParam("tip") Integer tip, ModelMap map, HttpSession session) {
        System.out.println("登录名：" + loginname + "密码：" + password + "权限：" + tip);
        if (tip == 1) {
            User user = new User();
            user.setLoginname(loginname);
            user.setPassword(password);
            User userNew = userService.selectUserLogin(user);
            if (userNew != null) {
                System.out.println(userNew.getUsername());
                System.out.println(userNew.toString());
                session.setAttribute("user_session", userNew);
                session.setAttribute("tip", tip);
                session.setAttribute("id", userNew.getId());
                return "index";
            }
            map.addAttribute("msg", "账号或密码错误");
            return "loginForm";
        }
        password = BaseCryptographyUtils.desEncodeHexString(password.trim(), desKey);
        Employee employee = new Employee();
        employee.setUsername(loginname);
        employee.setPassword(password);
        Employee employeeNew = employeeService.selectEmployeeByLogin(employee);
        if (employeeNew != null) {
            System.out.println(employeeNew.getUsername());
            System.out.println(employeeNew);
            session.setAttribute("user_session", employeeNew);
            session.setAttribute("tip", tip);
            session.setAttribute("id", employeeNew.getId());
            return "indexcustomer";
        }
        session.setAttribute("msg", "账号或密码错误");
        return "loginForm";
    }

    /**
     * 人脸识别登录user/employee
     *
     * @return
     */
    @GetMapping("/login/{tip}")
    public String doLogin(@PathVariable Integer tip) {
        if (tip == 1) {
            return "index";
        } else {
            return "indexcustomer";
        }
    }

    /**
     * 去采集人脸页
     * 1，用于登录注册
     * 2，登录
     * 3，考勤打卡
     *
     * @return
     */
    @GetMapping("/face/{useFor}")
    public String toScanFace(Model model, @PathVariable Integer useFor) {
        model.addAttribute("useFor", useFor);
        return "face/face";
    }

    @PostMapping("/match")
    @ResponseBody
    public Dto<Integer> toMatch(@RequestParam String message,
                                @RequestParam(required = false) Integer useFor,
                                HttpSession session) throws IOException {
//        System.out.println(message);
        System.out.println("进入人脸识别！");
        FaceClient faceClient = FaceClient.newInstance(APP_ID, API_KEY, SECRET_KEY);
        HashMap<String, String> options = new HashMap<String, String>();
        JSONObject res = faceClient.detect(message, BASE64, options);
        String errorMsg = res.getString("error_msg");
        if ("SUCCESS".equals(errorMsg)) {
            if (useFor == 1) {
                //注册人脸信息
                //当前登录权限
                //获取当前登录用户的id,注册人脸信息使用
                Integer id = (Integer) session.getAttribute("id");
                Integer tip = (Integer) session.getAttribute("tip");
                String faceToken = null;
                String group = null;
                if (tip == 1) {
                    group = "user";
                } else {
                    group = "employee";
                }
                faceToken = addFace(faceClient, id, message, BASE64, group, options);
                logger.info("注册的图片：" + faceToken);
                int count = empService.updateFaceToken(faceToken, id, tip);
                logger.info("存入数据库情况：" + count);
                if (count > 0) {
                    //注意不要返回信息错了
                    return DtoUtil.returnSuccess("注册成功！");
                } else {
                    return DtoUtil.returnFail("注册失败！");
                }
            } else if (useFor == 2) {
                return loginByFace(faceClient, message, BASE64, "user,employee", options, session);
            } else if (useFor == 3) {
                return DtoUtil.returnFail();
            }
        }
        return DtoUtil.returnFail();
    }

    /**
     * 将获取到的人脸信息存储到人脸库
     *
     * @param faceClient
     * @param id
     * @param base64
     * @param imageType
     * @param group
     * @param options
     * @return String
     */
    private String addFace(FaceClient faceClient, Integer id, String base64, String imageType, String group, HashMap<String, String> options) {
        //人脸注册
        String faceToken = faceClient.addFace(id, base64, BASE64, group, options);
        return faceToken;
    }

    /**
     * 人脸搜索登录
     *
     * @param faceClient
     * @param base64
     * @param imageType
     * @param group
     * @param options
     * @param session
     * @return Dto<Integer>
     */
    private Dto<Integer> loginByFace(FaceClient faceClient, String base64, String imageType, String group, HashMap<String, String> options, HttpSession session) {
        JSONObject search = faceClient.search(base64, BASE64, group, options);
        boolean match = faceClient.verifyForSearch(search);
        if (match) {
            //匹配数据库对的表名和用户id
            String table = faceClient.getString(search, "group_id");
            String id = faceClient.getString(search, "user_id");
            int uid = Integer.parseInt(id);
            if ("user".equalsIgnoreCase(table)) {
                //根据id查询出管理员
                User user = empService.getUserById(uid);
                if (user != null) {
                    //存入session登录用户信息
                    session.setAttribute(Constants.USER_SESSION, user);
                    Integer tip = 1;
                    //存入session域管理权限
                    session.setAttribute("tip", tip);
                    return DtoUtil.returnSuccess("管理员登录成功！", tip);
                }
            } else {
                Employee emp = empService.getEmpById(uid);
                if (emp != null) {
                    session.setAttribute(Constants.USER_SESSION, emp);
                    Integer tip = 2;
                    session.setAttribute("tip", tip);
                    return DtoUtil.returnSuccess("员工登录成功！", tip);
                }
            }
        }
        return DtoUtil.returnFail();
    }

    /**
     * 管理员登录后的跳转页
     *
     * @return
     */
    @GetMapping("/index")
    public String login() {
        return "index";
    }

    /**
     * 员工登录后的跳转页
     *
     * @return
     */
    @GetMapping("/indexcustomer")
    public String loginFailed() {
        return "indexcustomer";
    }

}
